package com.itheima.weirpc.loadbalancer;

import com.itheima.weirpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ClassName: RoundRobinLoadBalancer
 * Package: com.itheima.weirpc.loadbalancer.LoadBalancer
 * Description:
 *      轮询负载均衡器
 * @Author 看到风
 * @Create 2024/12/13 11:04
 * @Version 1.0
 */
public class RoundRobinLoadBalancer implements LoadBalancer{

    /**
     * 当前轮询的下标  使用JUC包的AtomicInteger实现原子计数器，防止并发冲突问题。
     */
    private final AtomicInteger currentIndex = new AtomicInteger(0);
    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if(serviceMetaInfoList.isEmpty()){
            return null;
        }
        //只有一个服务，无需轮询
        int size = serviceMetaInfoList.size();
        if(size==1){
            return serviceMetaInfoList.get(0);
        }
        //取模算法轮询
        int index = currentIndex.getAndIncrement()%size;
        return serviceMetaInfoList.get(index);
    }
}
